import collections
from django.shortcuts import render, redirect, HttpResponse
from django.db.models import Count
from web import models


def dashboard(request, project_id):
    # 项目参与者*****************
    userlist = models.ParticipatorInfo.objects.filter(project_id=project_id).values('participator_id',
                                                                                    'participator__user_name')
    # 先获取所有的状态，并组装成 有序 字典*******************
    status_dict = collections.OrderedDict()  # 创建一个有序字段，适用于py3.6及之前的版本
    for item in models.Issues.status_choices:
        status_dict[item[0]] = {"text": item[1], "count": 0}
    # 分组查询，按status分组进行统计
    status_data = models.Issues.objects.filter(project_id=project_id).values('status').annotate(heji=Count('id'))
    # print(status_data) <QuerySet [{'status': 1, 'heji': 4}, {'status': 2, 'heji': 2}, {'status': 6, 'heji': 1}]>
    for item in status_data:
        status_dict[item['status']]['count'] = item['heji']
    # 动态-获取该项目最新的10条动态
    # issues_top10 = models.Issues.objects.filter(project_id=project_id).order_by('-id')[0:10]
    # issues_top10 = models.Issues.objects.filter(project_id=project_id,assign__isnull=False).order_by('-id')[0:10]
    issues_top10 = models.IssuesReply.objects.filter(reply_type=1,issues__project_id=project_id).order_by('-id')[0:10]
    data = {
        "user_list": userlist,
        "status_dict": status_dict,
        "issues_top10": issues_top10,
    }
    return render(request, 'dashboard.html', data)

